package com.cyzy.homework.controller;

import com.cyzy.homework.common.Result;
import com.cyzy.homework.dto.HomeworkDTO;
import com.cyzy.homework.dto.UserDTO;
import com.cyzy.homework.service.HomeworkService;
import com.cyzy.homework.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 带用户信息的作业控制器
 * 整合用户信息和作业信息的展示
 */
@RestController
@RequestMapping("/api/homework-with-user")
@CrossOrigin(origins = "*")
public class HomeworkWithUserController {
    
    @Autowired
    private HomeworkService homeworkService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取作业页面的完整信息
     * 包括当前用户信息、健康码状态、作业列表等
     */
    @GetMapping("/page-info")
    public Result<Map<String, Object>> getHomeworkPageInfo(
            @RequestParam Integer userId,
            @RequestParam(required = false) String classId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Map<String, Object> pageInfo = new HashMap<>();
            
            // 获取当前用户信息（包含健康码）
            UserDTO currentUser = userService.getUserById(userId);
            pageInfo.put("currentUser", currentUser);
            
            // 获取作业列表
            if (classId != null && !classId.trim().isEmpty()) {
                Sort sort = Sort.by("createTime").descending();
                Pageable pageable = PageRequest.of(page, size, sort);
                Page<HomeworkDTO> homeworks = homeworkService.getHomeworksByClassId(classId, pageable);
                pageInfo.put("homeworks", homeworks);
            }
            
            // 获取可切换的用户列表（用于用户切换功能）
            List<UserDTO> switchableUsers = userService.getAllStudents();
            switchableUsers.addAll(userService.getAllTeachers());
            pageInfo.put("switchableUsers", switchableUsers);
            
            // 获取健康码统计信息
            Map<String, Object> healthStats = getHealthCodeStatistics();
            pageInfo.put("healthStats", healthStats);
            
            return Result.success("获取作业页面信息成功", pageInfo);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户切换接口
     */
    @PostMapping("/switch-user")
    public Result<Map<String, Object>> switchUser(
            @RequestParam Integer newUserId,
            @RequestParam(required = false) String classId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取新用户信息
            UserDTO newUser = userService.getUserById(newUserId);
            result.put("currentUser", newUser);
            
            // 根据新用户信息重新获取作业列表
            if (classId != null && !classId.trim().isEmpty()) {
                Sort sort = Sort.by("createTime").descending();
                Pageable pageable = PageRequest.of(page, size, sort);
                Page<HomeworkDTO> homeworks = homeworkService.getHomeworksByClassId(classId, pageable);
                result.put("homeworks", homeworks);
            }
            
            return Result.success("用户切换成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户健康码状态
     */
    @GetMapping("/health-code/{userId}")
    public Result<UserDTO> getHealthCode(@PathVariable Integer userId) {
        try {
            UserDTO userWithHealthCode = userService.getUserHealthCode(userId);
            return Result.success("获取健康码成功", userWithHealthCode);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取班级学生健康码统计
     */
    @GetMapping("/class/{classId}/health-stats")
    public Result<Map<String, Object>> getClassHealthStats(@PathVariable Integer classId) {
        try {
            List<UserDTO> students = userService.getStudentsByClassId(classId);
            
            Map<String, Object> stats = new HashMap<>();
            long greenCode = students.stream().filter(s -> s.getHealthCodeStatus() == 0).count();
            long yellowCode = students.stream().filter(s -> s.getHealthCodeStatus() == 1).count();
            long redCode = students.stream().filter(s -> s.getHealthCodeStatus() == 2).count();
            
            stats.put("total", students.size());
            stats.put("greenCode", greenCode);
            stats.put("yellowCode", yellowCode);
            stats.put("redCode", redCode);
            stats.put("students", students);
            
            return Result.success("获取班级健康码统计成功", stats);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前用户的作业提交状态
     */
    @GetMapping("/user/{userId}/homework-status")
    public Result<Map<String, Object>> getUserHomeworkStatus(
            @PathVariable Integer userId,
            @RequestParam String classId) {
        try {
            // 获取用户信息
            UserDTO user = userService.getUserById(userId);
            
            // 获取班级作业列表
            Sort sort = Sort.by("createTime").descending();
            Pageable pageable = PageRequest.of(0, 100, sort); // 获取更多作业用于统计
            Page<HomeworkDTO> homeworks = homeworkService.getHomeworksByClassId(classId, pageable);
            
            Map<String, Object> status = new HashMap<>();
            status.put("user", user);
            status.put("totalHomeworks", homeworks.getTotalElements());
            // TODO: 添加已提交、未提交、过期等统计信息
            
            return Result.success("获取用户作业状态成功", status);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取健康码统计信息
     */
    private Map<String, Object> getHealthCodeStatistics() {
        List<UserDTO> allStudents = userService.getAllStudents();
        
        Map<String, Object> stats = new HashMap<>();
        long greenCode = allStudents.stream().filter(s -> s.getHealthCodeStatus() == 0).count();
        long yellowCode = allStudents.stream().filter(s -> s.getHealthCodeStatus() == 1).count();
        long redCode = allStudents.stream().filter(s -> s.getHealthCodeStatus() == 2).count();
        
        stats.put("total", allStudents.size());
        stats.put("greenCode", greenCode);
        stats.put("yellowCode", yellowCode);
        stats.put("redCode", redCode);
        
        return stats;
    }
}


























